<template>
  <div class="wrapper">
    <header>
      <p>确认订单</p>
    </header>

    <!-- 温馨提示 -->
    <div class="warm-tip">
      <div class="warm-tip-left">
        <i class="fa fa-volume-up"></i>
        <span class="warm-tip-text">温馨提示：请适量点餐，避免浪费</span>
      </div>
      <i class="fa fa-times warm-tip-close"></i>
    </div>

    <!-- 配送方式 -->
    <div class="delivery-method">
      <div class="delivery-tabs">
        <div class="delivery-tab active">外卖配送</div>
        <div class="delivery-tab">到店自取</div>
      </div>
    </div>

    <!-- 地址信息 -->
    <div class="order-info">
      <div class="order-info-address" @click="toUserAddress">
        <div class="address-info">
          <div class="address-title">请选择收货地址</div>
          <div class="address-detail">{{deliveryAddress?.address || '选择收货地址'}}</div>
        </div>
        <i class="fa fa-angle-right address-right"></i>
      </div>

      <!-- 配送时间 -->
      <div class="delivery-time">
        <div class="delivery-time-left">立即送出</div>
        <div class="delivery-time-right">
          <span>预计10:34-10:49送达</span>
          <i class="fa fa-angle-right"></i>
        </div>
      </div>
      <div class="delivery-notice">
        因配送距离较远，送达时间可能波动
      </div>
    </div>

    <!-- 商家信息 -->
    <div class="business-info">
      <div class="business-name">{{business?.businessName}}</div>
    </div>

    <!-- 订单明细 -->
    <ul class="order-detailed">
      <li v-for="item in cartArr" :key="item.foodId">
        <div class="order-detailed-left">
          <img :src="item.foodImg">
          <p>{{item.foodName}} x {{item.quantity}}</p>
        </div>
        <p>&#165;{{(parseFloat(item.foodPrice) * item.quantity).toFixed(2)}}</p>
      </li>
    </ul>

    <!-- 其他费用 -->
    <div class="order-fee">
      <div class="fee-item">
        <div class="fee-label">
          <span>打包费</span>
          <i class="fa fa-question-circle"></i>
        </div>
        <div class="fee-value">¥4</div>
      </div>
      <div class="fee-item">
        <div class="fee-label">
          <span>配送费</span>
          <i class="fa fa-question-circle"></i>
        </div>
        <div class="fee-value">¥{{parseFloat(business?.deliveryPrice || 0).toFixed(2)}}</div>
      </div>
      <div class="fee-item">
        <div class="fee-label">店铺满35减3</div>
        <div class="fee-value discount">-¥3</div>
      </div>
      <div class="fee-item">
        <div class="fee-label">首次光顾立减</div>
        <div class="fee-value discount">-¥1</div>
      </div>
      <div class="fee-item">
        <div class="fee-label">红包/抵用券</div>
        <div class="fee-value discount">-¥13</div>
      </div>
    </div>

    <!-- 底部结算 -->
    <div class="total">
      <div class="total-left">
        <div>合计 ¥{{totalSettle}}</div>
        <div class="discount-info">已优惠¥50</div>
      </div>
      <div class="total-right" @click="toPayment">
        提交订单
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const router = useRouter()
const route = useRoute()

const businessId = ref(route.query.businessId)
const business = ref({})
const cartArr = ref([])
const user = ref({})
const deliveryAddress = ref(null)

// 计算总价
const totalPrice = computed(() => {
  let total = 0
  for (let item of cartArr.value) {
    const price = parseFloat(item.foodPrice || 0)
    const quantity = parseInt(item.quantity || 0, 10)
    total += price * quantity
  }
  return total.toFixed(2)
})

// 获取购物车信息
const loadCartData = async () => {
  try {
    const response = await request({
      url: '/CartController/listCart',
      method: 'get',
      params: {
        userId: user.value.userId,
        businessId: businessId.value
      }
    })
    
    console.log('购物车原始数据:', response.data)
    
    // 获取食品列表
    const foodResponse = await request({
      url: '/FoodController/listFoodByBusinessId',
      method: 'get',
      params: {
        businessId: businessId.value
      }
    })
    
    const foodMap = new Map(foodResponse.data.map(food => [food.foodId, food]))
    
    // 处理购物车数据
    cartArr.value = response.data.map(item => {
      const food = foodMap.get(item.foodId)
      if (!food) {
        console.error('未找到对应的食品信息:', item)
        return null
      }
      
      return {
        cartId: item.cartId,
        foodId: item.foodId,
        foodName: food.foodName,
        foodPrice: parseFloat(food.foodPrice || 0),
        foodImg: food.foodImg,
        quantity: parseInt(item.quantity || 0, 10),
        businessId: item.businessId
      }
    }).filter(item => item !== null) // 过滤掉无效数据

    console.log('处理后的购物车数据:', cartArr.value)
  } catch (error) {
    console.error('获取购物车信息错误:', error.response || error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('获取购物车信息失败')
    }
  }
}

onMounted(async () => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  user.value = JSON.parse(sessionStorage.getItem('user'))
  if (!user.value) {
    ElMessage.warning('用户信息已失效，请重新登录')
    router.push('/login')
    return
  }

  // 获取送货地址
  const storedAddress = localStorage.getItem(user.value.userId)
  if (storedAddress) {
    deliveryAddress.value = JSON.parse(storedAddress)
  }

  try {
    // 获取商家信息
    const businessResponse = await request({
      url: '/BusinessController/getBusinessById',
      method: 'get',
      params: {
        businessId: businessId.value
      }
    })
    business.value = businessResponse.data
    console.log('商家信息:', business.value)
    
    // 加载购物车数据
    await loadCartData()
  } catch (error) {
    console.error('初始化数据错误:', error.response || error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('获取商家信息失败')
    }
  }
})

// 计算实付金额
const totalSettle = computed(() => {
  const deliveryPrice = parseFloat(business?.deliveryPrice || 0)
  return (parseFloat(totalPrice.value) + deliveryPrice).toFixed(2)
})

// 跳转到地址选择
const toUserAddress = () => {
  router.push({
    path: '/userAddress',
    query: { businessId: businessId.value }
  })
}

// 提交订单
const toPayment = () => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!deliveryAddress.value) {
    ElMessage.warning('请选择送货地址')
    return
  }

  request({
    url: '/OrdersController/createOrders',
    method: 'post',
    headers: {
      'Authorization': token,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: qs.stringify({
      userId: user.value.userId,
      businessId: businessId.value,
      daId: deliveryAddress.value.daId,
      orderTotal: totalSettle.value
    })
  }).then(response => {
    if (response.data > 0) {
      ElMessage.success('下单成功')
      router.push({
        path: '/payment',
        query: { orderId: response.data }
      })
    } else {
      ElMessage.error('下单失败')
    }
  }).catch(error => {
    console.error('提交订单错误:', error.response || error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('下单失败')
    }
  })
}

// 性别过滤器
const sexFilter = (value) => {
  return value === 1 ? '先生' : '女士'
}
</script>
<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  min-height: 100vh;
  background: #f5f5f5;
}
/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 44px;
  background-color: #0097FF;
  color: #fff;
  font-size: 16px;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
/****************** 温馨提示样式 ******************/
.warm-tip {
  margin-top: 44px;
  padding: 8px 12px;
  background: #fff5e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.warm-tip-left {
  display: flex;
  align-items: center;
  gap: 4px;
}
.warm-tip-left i {
  color: #ff6b01;
  font-size: 16px;
}
.warm-tip-text {
  color: #ff6b01;
  font-size: 13px;
}
.warm-tip-close {
  color: #999;
  font-size: 16px;
  cursor: pointer;
}
/****************** 配送方式选择 ******************/
.delivery-method {
  background: #fff;
  margin-bottom: 10px;
}
.delivery-tabs {
  display: flex;
  border-bottom: 1px solid #f5f5f5;
}
.delivery-tab {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  color: #666;
  position: relative;
  cursor: pointer;
}
.delivery-tab.active {
  color: #0097FF;
}
.delivery-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background: #0097FF;
}
/****************** 地址选择样式 ******************/
.order-info {
  background: #fff;
  margin-bottom: 10px;
}
.order-info-address {
  padding: 15px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f5f5f5;
}
.address-info {
  flex: 1;
  padding-right: 15px;
}
.address-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}
.address-detail {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}
.address-right {
  color: #666;
  font-size: 16px;
}
/****************** 配送时间 ******************/
.delivery-time {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}
.delivery-time-left {
  font-size: 14px;
  color: #333;
}
.delivery-time-right {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #0097FF;
  font-size: 14px;
}
.delivery-notice {
  padding: 8px 12px;
  font-size: 12px;
  color: #0097FF;
  background: #f0f9ff;
}
/****************** 商家信息 ******************/
.business-info {
  background: #fff;
  margin-bottom: 10px;
  padding: 15px 12px;
}
.business-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-bottom: 12px;
}
/****************** 订单明细样式 ******************/
.order-detailed {
  background: #fff;
  margin-bottom: 10px;
}
.order-detailed li {
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f5f5f5;
}
.order-detailed-left {
  display: flex;
  align-items: center;
  gap: 10px;
}
.order-detailed-left img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}
.order-detailed-left p {
  font-size: 14px;
  color: #333;
}
.order-detailed li p:last-child {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
/****************** 其他费用 ******************/
.order-fee {
  background: #fff;
  margin-bottom: 60px;
}
.fee-item {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}
.fee-label {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}
.fee-value {
  font-size: 14px;
  color: #333;
}
.fee-value.discount {
  color: #ff4e00;
}
/****************** 底部结算栏 ******************/
.total {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}
.total-left {
  flex: 2;
  padding: 0 15px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}
.total-right {
  flex: 1;
  height: 100%;
  background: #0097FF;
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.discount-info {
  font-size: 12px;
  color: #ff4e00;
  margin-top: 2px;
}
</style>